<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="100px"
            id="form"
          >
            <el-form-item label="创建日期：" prop="createTime">
              <el-date-picker
                v-model="createTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
                @change="getArticleList"
              />
            </el-form-item>
            <el-form-item label="" prop="mode">
              <el-select
                v-model.trim="form.mode"
                placeholder="采购方式"
                class="wid100 methods"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(modeList, index) in list.modeList"
                  :key="index"
                  :label="modeList"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
              <el-select
                v-show="form.mode == 1"
                v-model.trim="form.buyer_id"
                placeholder="采购员"
                class="wid220 marginLeft5s"
                filterable
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(buyer, index) in list.buyer"
                  :key="index"
                  :label="buyer"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>

              <el-select
                v-show="form.mode == 2"
                v-model.trim="form.supplier_id"
                placeholder="供应商"
                class="wid220 marginLeft5s"
                filterable
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(supplier, index) in list.supplier"
                  :key="index"
                  :label="supplier"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>

              <el-select
                v-show="form.mode == 3"
                v-model.trim="form.supplier_id"
                placeholder="供应商"
                class="wid220 marginLeft5s"
                filterable
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(supply, index) in list.direct_supply"
                  :key="index"
                  :label="supply"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>

              <el-select
                v-show="!form.mode"
                v-model.trim="formall"
                placeholder="供应商"
                class="wid220 marginLeft5s"
                filterable
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="付款方式：" prop="pay_type">
              <el-select
                v-model.trim="form.pay_type"
                placeholder="付款方式"
                class="wid220"
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(pay_type_list, index) in list.pay_type_list"
                  :key="index"
                  :label="pay_type_list"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
              <el-button @click="exportb">导出</el-button>
            </MainFormBtn>
            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-show="moredata">
                <el-form-item label="结算单：" prop="order_sn">
                  <el-input
                    v-model.trim="form.order_sn"
                    placeholder="结算单"
                    clearable
                    class="wid220"
                  ></el-input>
                </el-form-item>
                <el-form-item label="账期：" prop="payment_days">
                  <el-date-picker
                    v-model="form.payment_days"
                    type="month"
                    placeholder="选择月"
                    value-format="yyyy-MM"
                    @change="getArticleList"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="状态：" prop="status">
                  <el-select
                    v-model.trim="form.status"
                    placeholder="状态"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value="0"></el-option>
                    <el-option label="正常" value="2"></el-option>
                    <el-option label="作废" value="1"></el-option>
                  </el-select>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                    <el-button @click="exportb">导出</el-button>
                  </MainFormBtn>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div>
            <router-link to="/financial/red/detail">
              <el-button> 结算明细</el-button>
            </router-link>
          </div>
        </div>
        <div class="main_table">
          <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list.data"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
          :header-cell-class-name="this.$verticaline"
          :height="borderHeight"
          :header-cell-style="tableHeightStyle"
          @header-dragend="changeTableWidth"
          @row-dblclick="rowDblclick"
        >
          <el-table-column type="selection" align="center"></el-table-column>
          <el-table-column label="结算单号" prop="order_sn"
          :width="tableWidth[hash+'order_sn']" />
          <el-table-column label="账期" prop="payment_days"
          :width="tableWidth[hash+'payment_days']">
            <template slot-scope="scope">{{ scope.row.payment_days }}</template>
          </el-table-column>
          <el-table-column label="采购方式"
          prop="mode"
          :width="tableWidth[hash+'mode']">
            <template slot-scope="scope">{{
              list.modeList[scope.row.mode]
            }}</template>
          </el-table-column>
          <el-table-column label="采购员/供应商"
          prop="buyer_id"
          :width="tableWidth[hash+'buyer_id'] || 140">
            <template slot-scope="scope">
              <!-- a == 1 ? '是' : (a == 2 ?  '不是' : '未知') -->
              {{
                scope.row.mode == 1
                  ? list.buyer[scope.row.buyer_id]
                  : scope.row.mode == 2
                  ? list.supplier[scope.row.supplier_id]
                  : list.direct_supply[scope.row.supplier_id]
              }}
            </template>
          </el-table-column>
          <el-table-column label="付款金额" prop="paid" 
          :width="tableWidth[hash+'paid']"/>
          <el-table-column label="抹零金额" prop="zero_money" 
          :width="tableWidth[hash+'zero_money']"/>
          <el-table-column label="付款方式" prop="pay_type"
          :width="tableWidth[hash+'pay_type']">
            <template slot-scope="scope">{{
              list.pay_type_list[scope.row.pay_type]
            }}</template>
          </el-table-column>

          <el-table-column label="状态" prop="status"
          :width="tableWidth[hash+'status']">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 0" style="color: #f56c6c">
                作废
              </span>
              <span v-else style="color: #03a98e"> 正常 </span>
            </template>
          </el-table-column>

          <el-table-column label="创建日期" prop="created_at"
          :width="tableWidth[hash+'created_at']">
            <template slot-scope="scope">{{
              parseTime(scope.row.created_at, "{y}-{m}-{d}")
            }}</template>
          </el-table-column>

          <el-table-column
            label="管理操作"
            align="center"
            fixed="right"
            prop="operate"
            :width="tableWidth[hash+'operate'] || 240"
            class-name="main_hei"
          >
            <template slot-scope="scope">
              <router-link :to="'/financial/red/see/' + scope.row.id">
                <el-link type="success">查看</el-link>
              </router-link>
              <el-link
                style="color: rgb(17, 138, 178)"
                @click="exportOrderiInfo(scope.row.id)"
                >导出</el-link
              >
              <el-link
                v-if="scope.row.status == 1"
                style="color: #f56c6c"
                @click="cancellation(scope.row.id)"
                >作废</el-link
              >
              <el-link @click="print(scope.row.id)">打印</el-link>
            </template>
          </el-table-column>
          </el-table>
        </div>
        <div class="main_num boxdq mg-t-10">
          <div class="main_num_l box">
            <p>
              付款金额：
              <em>{{ list.paid_money }}</em>
            </p>
            <p>
              抹零金额：
              <em>{{ list.zero_money }}</em>
            </p>
          </div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 导出 -->
    <el-dialog
      title="导出"
      :visible.sync="exportbuVisible"
      class="main_dialog dialog500"
    >
      <div v-if="selectArr.length == 0 ? true : false">
        <p class="exptitle">创建日期</p>
        <el-date-picker
          v-model="exportTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="datepicker"
        >
        </el-date-picker>
        <!-- <el-tooltip
          class="item"
          effect="dark"
          content="时间范围只能选择一个月之内"
          placement="bottom"
        >
          <i class="el-icon-question"></i>
        </el-tooltip> -->
      </div>
      <div v-if="selectArr.length == 0 ? true : false">
        <p class="exptitle company_name">采购方式</p>
        <el-select v-model.trim="mode" placeholder="采购方式" class="wid220">
          <el-option label="所有" value=""></el-option>
          <el-option
            v-for="(modeList, index) in list.modeList"
            :key="index"
            :label="modeList"
            :value="parseInt(index)"
          ></el-option>
        </el-select>
      </div>
      <div v-if="selectArr.length == 0 ? false : true" class="maintip">
        你已经选择了<span>{{ selectArr.length }}</span
        >行数据
      </div>
      <div class="isexportCheckbox">
        <el-checkbox v-model="goodspicker"
          >导出商品信息
          <el-tooltip
            class="item"
            effect="dark"
            content="默认勾选，导出全部的订单详情信息"
            placement="bottom"
          >
            <i class="el-icon-question"></i> </el-tooltip
        ></el-checkbox>
      </div>
      <div class="company_name_box" v-if="!goodspicker">
        <p class="exptitle company_name">商户名称</p>
        <el-checkbox-group v-model="selectTypeList">
          <el-checkbox
            v-for="(Header, index) in exportGoodsList"
            :key="index"
            :label="Header.id"
            :disabled="Header.disabled"
            >{{ Header.name }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportbuVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportConfirm" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 打印子组件 -->
    <order-print
      ref="printTemplate"
      v-show="false"
      id="printname"
    ></order-print>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  advice_index,
  get_header,
  export_advice_list,
  export_advice_detailList,
  advice_setStatus,
} from "@/api/financial/financialRed";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { field_save } from "@/api/currency";
import dateOption from "@/options/dateOption";
import exportList from "@/options/export";
import OrderPrint from "@/views/order/orderPrint.vue";
import { parseTime, exportMethod } from "@/utils/index";
export default {
  mixins: [mixins],
  components: {
    OrderPrint,
  },
  data() {
    return {
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 时间
      parseTime,
      exportMethod,
      // 列表数据
      list: {
        list: [],
      },
      listLoading: false,
      // 搜索
      form: {
        pay_type: null,
        order_sn: "",
        start_time: "",
        end_time: "",
        mode: null,
        buyer_id: null,
        supplier_id: null,
        payment_days: "",
        status: "",
      },
      formall: "",
      createTime: [],
      pickerOptions: dateOption,
      // 更多
      moredata: false,

      // 导出
      exportbuVisible: false,
      exportTime: "",
      // 选择全部
      selectArr: [],
      selectname: "",
      // 默认的导出表头信息

      selectTypeList: [],
      goodspicker: true, //商品信息 true
      exportGoodsList: exportList.financialList,
      mode: "", //导出时选择的采购方式
    };
  },
  watch: {
    "form.mode": {
      handler(val) {
        if (val == 1) {
          this.form.supplier_id = null;
        } else if (val == 2) {
          this.form.buyer_id = null;
        } else if (!val) {
          this.form.supplier_id = null;
          this.form.buyer_id = null;
        }
      },
      deep: true,
    },
  },
  activated() {
    // 列表
    this.advice_index();
  },
  created() {
    this.getNumerical(200);
  },
  methods: {
    //  表格双击跳转详情页面
    rowDblclick(row, column, event) {
      this.$router.push('/financial/red/see/' + row.id)
    },
    startGetting() {
      this.getSearchFor();
    },
    // 搜索并折叠搜索条件
    getSearchFor() {
      this.getArticleList();
    },
    // 作废订单
    cancellation(id) {
      this.$confirm("是否作废该订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          {
            id,
          }
        );
        advice_setStatus(data).then((res) => {
          // console.log(res)
          if (res.errcode == 0) {
            this.$message({
              type: "success",
              message: "作废成功",
            });
            this.advice_index();
          } else {
            this.$message({
              type: "error",
              message: res.errmsg,
            });
          }
        });
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.advice_index();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.form.supplier_id = null;
      this.form.buyer_id = null;
      this.getArticleList();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.advice_index();
    },
    changePage(page) {
      this.current.page = page;
      this.advice_index();
    },
    // 列表
    advice_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      advice_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";

      return form;
    },
    // 导出
    exportb() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      get_header(data).then((res) => {
        if (res.errcode == 0) {
          this.selectTypeList = res.data.list.type_13;
        }
      });
      this.exportbuVisible = true;
    },
    exportConfirm() {
      let selectList = [];
      this.exportGoodsList.map((e) => {
        this.selectTypeList.map((p) => {
          if (e.id == p) {
            selectList.push(e.id);
            return;
          }
        });
      });
      // 储存导出的订单字段
      let data1 = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { type: 13 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          type: 13,
          fields: JSON.stringify(selectList),
        }
      );
      field_save(data1).then((res) => {
        if (res.errcode != 0) {
          this.$message.success("导出结算列表表头设置错误");
        }
      });
      let ids = [];
      if (this.selectArr.length > 0) {
        this.selectArr.forEach((item) => {
          ids.push(item.id);
        });
      }
      ids = ids.join("-");
      let form = {
        ids: ids,
        start_time: "",
        list_head: selectList.join("-"),
        end_time: "",
        mode: this.mode,
        supplier_id: "",
        buyer_id: "",
      };
      if (this.exportTime) {
        form.start_time = this.exportTime[0];
        form.end_time = this.exportTime[1];
      }
      if (!form.ids && !form.start_time) {
        this.$message.error("请选择导出的订单或者导出的时间");
        return;
      }
      this.exportbuVisible = false;
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_advice_list(form)
        .then((res) => {
          this.exportMethod(res, "采购结算列表单", notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },
    // 导出时间范围
    datepicker(val) {
      let start = "";
      let end = "";
      if (val) {
        start = new Date(val[0]).getTime();
        end = new Date(val[1]).getTime();
        if (end - start > 30 * 24 * 60 * 60 * 1000) {
          this.$message.error("选择范围不能超过一个月，请重新选择");
          this.exportTime = "";
        }
      }
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
      console.log(this.selectArr);
    },
    // 打印
    print(id) {
      this.printid = id;
      this.$refs.printTemplate.$emit("demo", { id: id, type: "advice" });
    },
    exportOrderiInfo(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          id: id,
        }
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_advice_detailList(data)
        .then((res) => {
          this.exportMethod(res, "结算列表详情", notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: 100%;
    .mg-b-10 {
      margin-bottom: 10px;
    }
  }
}

// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
}
.company_name {
  padding-top: 15px;
}
.maintip {
  text-align: center;
  padding-top: 15px;
  font-size: 18px;
  span {
    display: inline;
    padding: 18px 0;
    color: red;
  }
}
.isexportCheckbox {
  margin-top: 15px;
}
.company_name_box {
  .company_name {
    padding-top: 0;
  }
}
/deep/.main_table .el-table--small td.main_hei .cell {
  display: flex;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
.wid100 {
  width: 100px;
}

.marginLeft5s {
  margin-left: -5px;
}
/deep/.methods .el-input__inner {
  border: none;
}
</style>
